<template>
  <div>
    <Chart :cdata="cdata" />
  </div>
</template>

<script>
import Chart from './chart.vue'
import { dateFormat } from "@/util/date";
import { lastTicketList } from "@/api/statics/dataview";
export default {
  props: {
    shop: {
      type: String,
      default: () => ''
    }
  },
  data () {
    return {
      drawTiming: null,
      cdata: {
        year: null,
        weekCategory: [],
        radarData: [],
        radarDataAvg: [],
        maxData: 12,
        weekMaxData: [],
        weekLineData: []
      }
    }
  },
  components: {
    Chart,
  },
  watch: {
    shop() {
      this.setData();
    }
  },
  mounted () {
    this.drawTimingFn();
  },
  beforeDestroy () {
    clearInterval(this.drawTiming);
  },
  methods: {
    drawTimingFn () {
      this.setData();
      this.drawTiming = setInterval(() => {
        this.setData();
      }, 30000);
    },
    setData () {
      // 清空轮询数据
      this.cdata.weekCategory = [];
      this.cdata.weekMaxData = [];
      this.cdata.weekLineData = [];
      this.cdata.radarData = [];
      this.cdata.radarDataAvg = [];

      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      const params = {
        startTime: dateFormat(start, 'yyyy-MM-dd 00:00:00'),
        endTime: dateFormat(new Date(), 'yyyy-MM-dd 23:59:59')
      }
      if (this.shop && this.shop !== '') {
        params.shopName = this.shop
      }
      lastTicketList(params).then(res => {
        const resData = res.data.data

        let dateBase = new Date();
        this.cdata.year = dateBase.getFullYear();

        for (let i = 0; i < 7; i++) {
          // 日期
          let date = new Date();
          const month = date.getMonth() < 9 ? ('0' + (date.getMonth() + 1)) : (date.getMonth() + 1)
          const dateTime = (date.getDate() - i) < 9 ? ('0' + (date.getDate() - i)) : (date.getDate() - i)
          const dateStr = `${month}-${dateTime}`
          this.cdata.weekCategory.unshift(dateStr);

          let count = 0
          resData.forEach(item => {
            let createTime = item.datetime
            createTime = createTime.substring(5, 10)
            if (dateStr === createTime) {
              count++
            }
          })

          if (this.cdata.maxData < count) {
            this.cdata.maxData = count
          }
          this.cdata.weekMaxData.push(this.cdata.maxData);
          this.cdata.weekLineData.push(count);
        }
      })
    }
  }
};
</script>

<style lang="scss" scoped>
</style>
